package com.wzm.utils;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;

public class DBUtils {

    public final Logger logger = Logger.getLogger(this.getClass().getName());

    private Connection connection;
    private String url;
    private String username;
    private String password;

    public DBUtils() {
        // 从db配置文件夹中读取连接信息
        Properties properties = new Properties();
        try (FileInputStream input = new FileInputStream("db.properties")) {
            properties.load(input);
            this.url = properties.getProperty("db.url");
            this.username = properties.getProperty("db.username");
            this.password = properties.getProperty("db.password");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 创建新连接
    public void connect() throws SQLException {
        if (connection == null || connection.isClosed()) {
            connection = DriverManager.getConnection(url, username, password);
            logger.info(String.format("创建 %s 数据连接成功",url));
        }
    }

    // 关闭数据库连接
    public void disconnect() throws SQLException {
        if (connection != null && !connection.isClosed()) {
            connection.close();
            logger.info(String.format("关闭 %s 数据连接成功",url));
        }
    }

    /***
     * 查询数据
     * @param query：为查询sql语句
     * @return
     * @throws SQLException
     */
    public List<Map<String, Object>> performSelect(String query) throws SQLException {
        connect();
        try {
            QueryRunner runner = new QueryRunner();
            return runner.query(connection, query, new MapListHandler());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ArrayList<>();
        } finally {
            // 关闭连接
            if (connection != null) {
                try {
                    disconnect();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws SQLException {
        DBUtils dbManager = new DBUtils();

        // Example usage: No need to manually connect or disconnect
        List<Map<String, Object>> results = dbManager.performSelect("SELECT * FROM users");
        for (Map<String, Object> row : results) {
            System.out.println(row);
        }
    }
}
